<?php


namespace app\model;


use think\facade\Db;
use think\Model;
use utils\Define;

class MoneyLog extends Model
{


    /**
     * @param $uid
     * @param $before_money
     * @param $money
     * @param $type
     * @param int $state
     * @param string $intro
     * @return bool
     */
    public static function SetUserMoney($uid, $before_money, $money, $type, $state = 1, $intro = '')
    {
        $money_log = array(
            'user_id' => $uid,
            'money' => $money,
            'type' => $type,
            'state' => $state,
            'before_money' => $before_money,
            'intro' => $intro,

        );
        if ($state == 1) {
            $money_log['after_money'] = $before_money + $money;
        } else {
            $money_log['after_money'] = $before_money - $money;
        }
        self::insert($money_log);
        return true;
    }


    /**
     * 日志
     */
    public function log($data)
    {
        $result = Db::name('money_log')
            ->field('*')
            ->where(['user_id' => $data->data['user_id'], 'state' => $data->data['state']])
            ->whereTime('created_time', 'between', [$data->data['start_time'], $data->data['end_time']])
            ->withAttr('type', function ($value, $data) {
                return $this->types($value);
            })
            ->paginate($data->data['limit'])
            ->toArray();
        $result['consume'] = abs(Db::name('money_log')->where(['user_id' => $data->data['user_id'], 'state' => 2])->sum('money')); //消耗
        $result['integral'] = $data->user->integral; //余额
        $result['get'] = $data->user->integral - $result['consume']; //余额
        return app('json')->json_success('成功', $result ?: []);
    }


    /**
     * 类型
     * @param $type
     * @return string
     */
    public function types($type)
    {
        $type = Define::MoneyLog[$type] ?: '';
        return $type;
    }
}